package com.example.safeassistan.login.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseActivity;
import com.example.safeassistan.base.BaseModel;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.utile.StringUtils;

import org.json.JSONException;
import org.json.JSONObject;


public class ForgetPassword extends BaseActivity implements View.OnClickListener {
    private TextView tvNext;
    private String phone="",password="",confirmpassword="",code="";
    private EditText etLoginPhone,etPassword,etPassword2;
    private ImageView ivClear;
    private TextView tvGetCode,tvLogin;
    private EditText etMsgCode;
    private ImageView ivBack;
    private ImageView ivEye1,ivEye2;
    private boolean isShow1=false,isShow2=false;

    private static final int CODE_ING = 1;//已发送，倒计时
    private static final int CODE_REPEAT = 2;//重新发送
    private int TIME = 60;// 倒计时60s

    public static void actionStart(Context context, String phone) {
        Intent intent = new Intent(context, ForgetPassword.class);
        intent.putExtra("phone", phone);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tvGetCode:
                getMobileMsgCode();
                break;
            case R.id.ivClear:
                etLoginPhone.setText("");
                break;
            case R.id.tvNext:
                //确定
                submitPwd();
                break;
            case R.id.ivBack:
                finish();
                break;
            case R.id.ivEye2:
                if(isShow2){
                    //切换不可见密码
                    ivEye2.setImageResource(R.mipmap.icon_no_eye);
                    //点一下可见
                    //设置代码可见 如果只设置TYPE_TEXT_VARIATION_PASSWORD则无效
                    etPassword2.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                    //改变状态值为假
                    isShow2=false;
                }else{
                    //切换可见密码
                    ivEye2.setImageResource(R.mipmap.icon_eye);
                    //点一下不可见
                    //设置代码不可见
                    etPassword2.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    //改变状态值为真
                    isShow2=true;
                }
                etPassword2.setSelection(etPassword2.getText().length());
                break;
            case R.id.ivEye1:
                if(isShow1){
                    //切换不可见密码
                    ivEye1.setImageResource(R.mipmap.icon_no_eye);
                    //点一下可见
                    //设置代码可见 如果只设置TYPE_TEXT_VARIATION_PASSWORD则无效
                    etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                    //改变状态值为假
                    isShow1=false;
                }else{
                    //切换可见密码
                    ivEye1.setImageResource(R.mipmap.icon_eye);
                    //点一下不可见
                    //设置代码不可见
                    etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    //改变状态值为真
                    isShow1=true;
                }
                etPassword.setSelection(etPassword.getText().length());
                break;
        }
    }

    /**
     * 获取手机验证码
     */
    private void getMobileMsgCode() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("mobile", phone);
            jsonObject.put("sendType", "2");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(this).doPost(UrlConstants.sms_send, "", jsonObject, BaseModel.class,new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                if (result instanceof BaseModel) {
                    BaseModel model = (BaseModel) result;
                    if (model.getCode() == 200) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                for (int i = 60; i > 0; i--) {
                                    handler.sendEmptyMessage(CODE_ING);
                                    if (i <= 0) {
                                        break;
                                    }
                                    try {
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                                handler.sendEmptyMessage(CODE_REPEAT);
                            }
                        }).start();
                    } else if(model.getCode()==500){
                        Toast.makeText(getContext(),model.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.e(TAG,msg);
            }
        });
    }


    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true); }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_forgetpassword;
    }

    @Override
    protected void initView() {
        setBackVisible(true);
        setTitleText("找回密码");
        ivClear=findViewById(R.id.ivClear);
        ivClear.setOnClickListener(this);
        ivEye2=findViewById(R.id.ivEye2);
        ivEye1=findViewById(R.id.ivEye1);
        ivEye2.setOnClickListener(this::onClick);
        ivEye1.setOnClickListener(this::onClick);
        etLoginPhone=findViewById(R.id.etLoginPhone);
        phone=getIntent().getStringExtra("phone");
        tvNext=findViewById(R.id.tvNext);
        tvNext.setOnClickListener(this);
        etLoginPhone.setText(phone);
        ivBack=findViewById(R.id.ivBack);
        ivBack.setOnClickListener(this::onClick);
        tvGetCode=findViewById(R.id.tvGetCode);
        tvGetCode.setOnClickListener(this::onClick);
        etMsgCode=findViewById(R.id.etMsgCode);
        tvLogin=findViewById(R.id.tvLogin);
        tvLogin.setOnClickListener(this::onClick);
        etLoginPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                try {
                    phone = charSequence.toString().trim();
                } catch (Exception e) {
                    phone = "";
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                ivClear.setVisibility(View.VISIBLE);
            }
        });
        etPassword=findViewById(R.id.etPassword);
        etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                try {
                    password = charSequence.toString().trim();
                } catch (Exception e) {
                    password = "";
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                ivClear.setVisibility(View.VISIBLE);
            }
        });
        etPassword2=findViewById(R.id.etPassword2);
        etPassword2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                try {
                    confirmpassword = charSequence.toString().trim();
                } catch (Exception e) {
                    confirmpassword = "";
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                ivClear.setVisibility(View.VISIBLE);
            }
        });
        etMsgCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                try {
                    code = charSequence.toString().trim();
                } catch (Exception e) {
                    code = "";
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                ivClear.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    protected void initData() {

    }


    private void submitPwd() {
        if(!StringUtils.isPhoneNumber(phone)){
            Toast.makeText(getContext(),"请输入符合规定的密码手机号",Toast.LENGTH_SHORT).show();
            return;
        }
        if(password.length()<6&&confirmpassword.length()<6){
            Toast.makeText(getContext(),"请输入符合规定长度的密码",Toast.LENGTH_SHORT).show();
            return;
        }

        if(!password.equals(confirmpassword)){
            Toast.makeText(getContext(),"两次输入新密码不一致",Toast.LENGTH_SHORT).show();
            return;
        }
        JSONObject  map = new JSONObject();
        try {
            map.put("code",code);
            map.put("newPassword", password);
            map.put("mobile", phone);
            map.put("oldPassword","");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(getContext()).doPost(UrlConstants.user_resetPassword, "", map, BaseModel.class, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                if (result instanceof BaseModel) {
                    BaseModel model = (BaseModel) result;
                    if(model.getCode()==200){
                        Toast.makeText(getContext(),"密码重置成功",Toast.LENGTH_SHORT).show();
                        finish();
                    }else {
                        Toast.makeText(ForgetPassword.this,model.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.e(TAG,msg);
            }
        });
    }



    @Override
    protected int getTitleBarType() {
        return TITLEBAR_NULL;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CODE_ING:
                    tvGetCode.setClickable(false);
                    tvGetCode.setText(--TIME + "s");
                    tvGetCode.setTextColor(getResources().getColor(R.color.gray9));
                    break;
                case CODE_REPEAT:
                    tvGetCode.setText("获取验证码");
                    tvGetCode.setClickable(true);
                    TIME = 60;
                    break;
                default:
                    break;
            }
        }
    };
}
